//
//  KLSendCarViewController.m
//  KunLun
//
//  Created by Mac on 2017/12/27.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLSendCarViewController.h"
#import "STTextView.h"
#import "KLChannelViewController.h"
#define XInsetValeu 20
#define nomalHeight 44
@interface KLSendCarViewController ()


@property(nonatomic, strong) UITextField                     *titleTextfiled;
@property(nonatomic, strong) STTextView                     *destextView;//描述
@property(nonatomic, strong) UITextField                     *carTypeTextfiled;

//上货地址
@property(nonatomic, strong) STButton                        *addressButton;
@property(nonatomic, strong) UITextField                     *detailAddTextfiled;//详细地址
//xiaohuo 地址
@property(nonatomic, strong) STButton                        *downAddressButton;
@property(nonatomic, strong) UITextField                     *downDetailAddTextfiled;//详细地址

@property(nonatomic, strong) UITextField                     *lineDesTextfiled;//路线描述

@property(nonatomic, strong) STTextView                     *goodDetailtextView;//货物详情

@property(nonatomic, strong) UITextField                     *nameTextfiled;
@property(nonatomic, strong) UITextField                     *phoneTextfiled;
@property(nonatomic, strong) UITextField                     *numberTextfiled;


@property(nonatomic, strong) UIScrollView                       *imageScrollView;
@property(nonatomic, strong) NSMutableArray                     *imageArray;
@property(nonatomic, assign)    CGFloat                         imageViewRight;
@property(nonatomic, strong) NSMutableArray                     *imageUrlsArray;
@end

@implementation KLSendCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发布货运";
    self.imageArray = [NSMutableArray new];
    [self.tableView st_autoAdjustAllResponder];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self configSubView];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    [self configHeaderView];
    [self configFooterView];
}
- (UIView*)viewformTextField:(UITextField*)textFiled title:(NSString*)title placeHolder:(NSString*)placeHolder{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 89)];
    UIView * shopNameView = [self headerViewWithTitle:title];
    [view addSubview:shopNameView];
    textFiled.frame = CGRectMake(XInsetValeu, shopNameView.bottom, UIScreenWidth - 2*XInsetValeu, 30);
    textFiled.placeholder = placeHolder;
    textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view addSubview:textFiled];
    
    UIView * line1 = [[UIView alloc] initWithFrame:CGRectMake(0, textFiled.bottom, UIScreenWidth, 0.5)];
    line1.backgroundColor = KL_lineColor;
    [view addSubview:line1];
    view.height = line1.bottom;
    return view;
}
- (UIView*)headerViewWithTitle:(NSString*)title{
    UIView * backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, nomalHeight)];
    backView.backgroundColor = [UIColor whiteColor];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(XInsetValeu, 0, UIScreenWidth - 2* XInsetValeu, nomalHeight)
                                                     text:title
                                                textColor:KL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [backView addSubview:titleLable];
    return backView;
}
- (void)configHeaderView{
    
    self.titleTextfiled = [UITextField new];
    self.carTypeTextfiled = [UITextField new];
    self.detailAddTextfiled = [UITextField new];
    self.downDetailAddTextfiled = [UITextField new];
    self.lineDesTextfiled = [UITextField new];
    self.nameTextfiled = [UITextField new];
    self.phoneTextfiled = [UITextField new];
    self.numberTextfiled = [UITextField new];
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 150)];
    header.backgroundColor = [UIColor whiteColor];
    

    UIView * biaotiView = [self viewformTextField:self.titleTextfiled
                                            title:@"标题"
                                      placeHolder:@"至少8个字"];
    [header addSubview:biaotiView];
    
    
    
    
//    UIView * desView = [self headerViewWithTitle:@"描述"];
//    desView.top = biaotiView.bottom;
//    [header addSubview:desView];
//    self.destextView = [[STTextView alloc] initWithFrame:CGRectMake(XInsetValeu, desView.bottom, UIScreenWidth - 2*XInsetValeu, 60)];
//    self.destextView.placeholder = @"请输入货运描述";
//    [self.destextView st_setBorderWith:1 borderColor:KL_lineColor cornerRadius:5];
//    [header addSubview:self.destextView];
    

    //货车类型
    UIView * carDetailView = [self viewformTextField:self.carTypeTextfiled
                                                  title:@"车辆类型"
                                            placeHolder:@"请输入车辆类型"];
    carDetailView.top = biaotiView.bottom;
    [header addSubview:carDetailView];
    
    __weak typeof(self) weakSelf =  self;
    //经营地址
    self.addressButton = [[STButton alloc] initWithFrame:CGRectMake(XInsetValeu, carDetailView.bottom, UIScreenWidth - 2*XInsetValeu, 40)
                                                   title:@"点击修改上货地址"
                                              titleColor:KL_firstTextColor
                                               titleFont:15
                                            cornerRadius:0
                                         backgroundColor:nil
                                         backgroundImage:nil
                                                   image:nil];
    [self.addressButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAddressButton];
    }];
    [header addSubview:self.addressButton];
    
    //详细地址
    UIView * detailAdressView = [self viewformTextField:self.detailAddTextfiled
                                                  title:@"详细地址"
                                            placeHolder:@"请输入详细上货地址"];
    detailAdressView.top = self.addressButton.bottom;
    [header addSubview:detailAdressView];
    
    //详细下火地址
    self.downAddressButton = [[STButton alloc] initWithFrame:CGRectMake(XInsetValeu, detailAdressView.bottom, UIScreenWidth - 2*XInsetValeu, 40)
                                                   title:@"点击修改下货地址"
                                              titleColor:KL_firstTextColor
                                               titleFont:15
                                            cornerRadius:0
                                         backgroundColor:nil
                                         backgroundImage:nil
                                                   image:nil];
    [self.downAddressButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedDownAddressButton];
    }];
    [header addSubview:self.downAddressButton];
    
    UIView * downDetailAdressView = [self viewformTextField:_downDetailAddTextfiled
                                                  title:@"详细地址"
                                            placeHolder:@"请输入详细下货地址"];
    downDetailAdressView.top = _downAddressButton.bottom;
    [header addSubview:downDetailAdressView];
    //路线描述
    UIView * lineView = [self viewformTextField:self.lineDesTextfiled
                                                  title:@"路线描述"
                                            placeHolder:@"请输入路线描述"];
    lineView.top = downDetailAdressView.bottom;
    [header addSubview:lineView];
    
    UIView * goodDetailView = [self headerViewWithTitle:@"货物详情"];
    goodDetailView.top = lineView.bottom;
    [header addSubview:goodDetailView];
    self.goodDetailtextView = [[STTextView alloc] initWithFrame:CGRectMake(XInsetValeu, goodDetailView.bottom, UIScreenWidth - 2*XInsetValeu, 60)];
    self.goodDetailtextView.placeholder = @"请输入货物详情描述,至少20个字";
    [self.goodDetailtextView st_setBorderWith:1 borderColor:KL_lineColor cornerRadius:5];
    [header addSubview:self.goodDetailtextView];
    
    //联系人
    UIView * nameView = [self viewformTextField:self.nameTextfiled
                                                  title:@"联系人"
                                            placeHolder:@"至少两个字"];
    nameView.top = self.goodDetailtextView.bottom;
    [header addSubview:nameView];
    
    //shoujihao
    UIView * phoneView = [self viewformTextField:self.phoneTextfiled
                                          title:@"手机号"
                                    placeHolder:@"请输入正确的手机号"];
    phoneView.top = nameView.bottom;
    self.phoneTextfiled.keyboardType = UIKeyboardTypeNumberPad;
    [header addSubview:phoneView];
    
    UIView * numberView = [self viewformTextField:self.numberTextfiled
                                           title:@"用车数量"
                                     placeHolder:@"请输入用车数量"];
    numberView.top = phoneView.bottom;
    self.numberTextfiled.keyboardType = UIKeyboardTypeNumberPad;
    [header addSubview:numberView];
    
    header.height = numberView.bottom;
    self.tableView.tableHeaderView = header;
}
- (void)configFooterView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = [UIColor whiteColor];
    
    STLabel * imagLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 0, UIScreenWidth - 2* self.insetX, 44)
                                                    text:@"上传封面图片:(提示，至少上传三张图片)"
                                               textColor:KL_firstTextColor
                                                    font:14
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    [footer addSubview:imagLable];
    
    //封面
    self.imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.insetX, imagLable.bottom, UIScreenWidth- 2*self.insetX, 110)];
    self.imageScrollView.contentSize = CGSizeMake(self.imageScrollView.width, 0);
    [footer addSubview:self.imageScrollView];
    [self resetImageScrollViewFrameWithAddImages:nil withScrollView:self.imageScrollView];
    
    
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, self.imageScrollView.bottom + 40, UIScreenWidth - 60, 44)
                                                        title:@"立即发布"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:10
                                              backgroundColor:KL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitButton];
    }];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    
    footer.height = confimButton.bottom + 20;
    self.tableView.tableFooterView = footer;
}
#pragma mark --Private Method
- (void)resetImageScrollViewFrameWithAddImages:(NSArray*)images withScrollView:(UIScrollView*)scrollView{
    
    for (UIView * view in scrollView.subviews) {
        [view removeFromSuperview];
    }
    //添加addImageView
    __weak typeof(self) weakSelf =  self;
    STButton * addImageButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)
                                                          title:@""
                                                     titleColor:nil
                                                      titleFont:0
                                                   cornerRadius:0
                                                backgroundColor:KL_backgroundColor
                                                backgroundImage:nil
                                                          image:[UIImage imageNamed:@"sz_xiangce"]];
    addImageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [addImageButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAddImageButton:sender];
    }];
    [scrollView addSubview:addImageButton];
    if (scrollView == self.imageScrollView) {
        self.imageViewRight = 100;
    }
    for (UIImage * image in images) {
        CGFloat right = 0;
        right = self.imageViewRight + 10;
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(right, 0, 100, 100)];
        imageView.image = image;
        [scrollView addSubview:imageView];
        self.imageViewRight = imageView.right;
        scrollView.contentSize = CGSizeMake(self.imageArray.count * 110 + 110, 0);
    
    }
    
}
- (void)onSelectedAddImageButton:(UIButton*)button{
    [self showSTImagePickerHandle:^(NSArray<STPhotoModel *> *array) {
        NSMutableArray *newImages = [NSMutableArray new];
        if (button.superview == self.imageScrollView) {
            self.imageArray = [NSMutableArray new];
        }
        for (STPhotoModel * model in array) {
            UIImage * image = model.originImage;
            image = image?image:model.thumbImage;
            if (button.superview == self.imageScrollView) {
                
                [self.imageArray addObject:image];
            }
            
            [newImages addObject:image];
        }
        
        [self resetImageScrollViewFrameWithAddImages:newImages withScrollView:(UIScrollView*)button.superview];
        
    } pickerBlock:^(UIImage *image) {
       // self.imageArray = [NSMutableArray new];
        if (button.superview == self.imageScrollView) {
            [self.imageArray addObject:image];
        }
        [self resetImageScrollViewFrameWithAddImages:self.imageArray withScrollView:(UIScrollView*)button.superview];
    }];
}
- (void)sendImages{
    self.imageUrlsArray = [NSMutableArray new];
    for (UIImage * image in self.imageArray) {
        [KLUtils sendQiNiuWithImage:image handle:^(NSString *imageUrl, NSString *errorDes) {
            [self.imageUrlsArray addObject:imageUrl];
            if ([self isCanSendRequest]) {
                [self sendGoodInfoRequest];
            }
        }];
    }
}
- (BOOL)isCanSendRequest{
    if (self.imageUrlsArray.count == self.imageArray.count ) {
        return YES;
    }
    return NO;
}
#pragma mark --Action Method

- (void)onSelectedAddressButton{
    
    STPickerViewController * vc = [[STPickerViewController alloc] initWithDefualtAreaPickerWithHandle:^(NSString *finshString, NSString *area, NSString *city, NSString *provence) {
        [self.addressButton setTitle:[NSString stringWithFormat:@"%@%@",provence,city] forState:UIControlStateNormal];
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelectedDownAddressButton{
    STPickerViewController * vc = [[STPickerViewController alloc] initWithDefualtAreaPickerWithHandle:^(NSString *finshString, NSString *area, NSString *city, NSString *provence) {
        [self.downAddressButton setTitle:[NSString stringWithFormat:@"%@%@",provence,city] forState:UIControlStateNormal];
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelectedCommitButton{
    if (self.titleTextfiled.text.length < 8) {
        [SVProgressHUD showErrorWithStatus:@"标题最少8个字"];
        return;
    }
//    if (!self.destextView.text.length) {
//        [SVProgressHUD showErrorWithStatus:@"请输入描述"];
//        return;
//    }
    if (!self.carTypeTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入所需车辆类型"];
        return;
    }
    if ([self.addressButton.currentTitle isEqualToString:@"点击修改上货地址"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择上货地址"];
        return;
    }
    if (!self.detailAddTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细上货地址"];
        return;
    }
    if ([self.downAddressButton.currentTitle isEqualToString:@"点击修改下货地址"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择下货地址"];
        return;
    }
    if (!self.downDetailAddTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细下货地址"];
        return;
    }
    
    if (!self.lineDesTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入路线描述"];
        return;
    }
    if (!self.goodDetailtextView.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入货物描述"];
        return;
    }
    if (!self.nameTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人"];
        return;
    }
    if (!self.phoneTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (!self.numberTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入货车数量"];
        return;
    }
    if (self.imageArray.count < 3) {
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
        return;
    }
    [SVProgressHUD showWithStatus:@"上传中"];
    if ([self isCanSendRequest]) {
        [self sendGoodInfoRequest];
        return;
    }
    [self sendImages];
}

#pragma mark --NetWork Method
- (void)sendGoodInfoRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/freight/applyfreight",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    
    if (self.titleTextfiled.text.length) {
        [dic setObject:self.titleTextfiled.text forKey:@"title"];
    }
    //描述没有
//    if (self.destextView.text.length) {
//       // [dic setObject:self.destextView.text forKey:@""];
//    }
    //车辆类型
    if (self.carTypeTextfiled.text.length) {
        [dic setObject:self.carTypeTextfiled.text forKey:@"vehicle"];
    }
    //地址
    if (self.addressButton.currentTitle.length && self.detailAddTextfiled.text.length) {
        NSString * stri = [NSString stringWithFormat:@"%@%@",self.addressButton.currentTitle,self.detailAddTextfiled.text];
        [dic setObject:stri forKey:@"cargo_address"];
    }
    //下或地址
    if (self.downAddressButton.currentTitle.length && self.downDetailAddTextfiled.text.length) {
        NSString * stri = [NSString stringWithFormat:@"%@%@",self.downAddressButton.currentTitle,self.downDetailAddTextfiled.text];
          [dic setObject:stri forKey:@"discargo_address"];
    }

    NSString * cover_map = [self.imageUrlsArray componentsJoinedByString:@","];
    [dic setObject:cover_map forKey:@"pictures"];

    //路线
    if (self.lineDesTextfiled.text.length) {
        [dic setObject:self.lineDesTextfiled.text forKey:@"address_describe"];
    }
    //详情
    if (self.goodDetailtextView.text.length) {
        [dic setObject:self.goodDetailtextView.text forKey:@"details"];
    }
    //name
    if (self.nameTextfiled.text.length) {
        [dic setObject:self.nameTextfiled.text forKey:@"name"];
    }
    //phone
    if (self.phoneTextfiled.text.length) {
        [dic setObject:self.phoneTextfiled.text forKey:@"phone"];
    }
    if (self.numberTextfiled.text.length) {
        [dic setObject:self.numberTextfiled.text forKey:@"inventory"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"发布成功"];
                                                 [self.navigationController popViewControllerAnimated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                  [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];

                                                
                                             }];
}
@end
